package com.acip.uuid.config;

import com.acip.uuid.segment.BusinessCosIdSegmentCache;
import com.acip.uuid.segment.BusinessCosIdSegmentChain;
import com.acip.uuid.util.TableNameConvertUtil;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * @ClassName CustomIdGenerator
 * @Description
 * @Author RayLiang
 * @Date 2022/11/28 16:58
 * @Version 1.0
 **/
public class CustomIdGenerator implements IdentifierGenerator {

    private final BusinessCosIdSegmentCache businessCosIdSegmentCache;
    private final String applcationName;

    public CustomIdGenerator(BusinessCosIdSegmentCache businessCosIdSegmentCache,String applicationName) {
        this.businessCosIdSegmentCache = businessCosIdSegmentCache;
        this.applcationName = applicationName.replaceAll("-","_").concat("_sequence");
    }

    @Override
    public Number nextId(Object entity) {
         String tableName = "";
        if(Objects.nonNull(entity)){
            TableName tableNameAnnotation = (TableName) entity.getClass().getAnnotation(TableName.class);
            if(Objects.nonNull(tableNameAnnotation)) {
                tableName = tableNameAnnotation.value();
                if (StringUtils.isEmpty(tableName)) {
                    tableName = TableNameConvertUtil.toSymbolCase(entity.getClass().getSimpleName());
                }
            }else{
                tableName = TableNameConvertUtil.toSymbolCase(entity.getClass().getSimpleName());
            }
        }else{
            tableName = this.applcationName;
        }
        BusinessCosIdSegmentChain businessCosIdGenerator = businessCosIdSegmentCache.getBusinessCosIdGenerator(tableName);
        return businessCosIdGenerator.getId();
    }
}
